<template>
  <t-dialog
    :visible="visible"
    title="商品详情"
    :width="900"
    @close="handleClose"
  >
    <div v-if="loading" class="loading">
      <t-loading size="large" />
    </div>

    <div v-else-if="detail" class="detail-container">
      <t-descriptions column="1" :column="2" :column-width="['150px', 'auto']">
        <t-descriptions-item label="商品ID">{{ detail.commodityId }}</t-descriptions-item>

        <t-descriptions-item label="商品图片">
          <img
            v-if="commodity.image"
            :src="commodity.image"
            style="width: 100px; height: 100px; object-fit: cover"
          />
        </t-descriptions-item>

        <t-descriptions-item label="商品标题">{{ commodity.title }}</t-descriptions-item>
        <t-descriptions-item label="售价">{{ commodity.price }}</t-descriptions-item>
        <t-descriptions-item label="原价">{{ commodity.originalPrice }}</t-descriptions-item>
        <t-descriptions-item label="链接">{{ commodity.link }}</t-descriptions-item>
        <t-descriptions-item label="排序号">{{ commodity.sortOrder }}</t-descriptions-item>
        <t-descriptions-item label="状态">
          <t-tag :theme="commodity.status === 1 ? 'success' : 'danger'">
            {{ commodity.status === 1 ? '正常' : '禁用' }}
          </t-tag>
        </t-descriptions-item>
        <t-descriptions-item label="标签">{{ commodity.tagsText }}</t-descriptions-item>
        <t-descriptions-item label="创建时间">{{ commodity.createdAt }}</t-descriptions-item>
        <t-descriptions-item label="更新时间">{{ commodity.updatedAt }}</t-descriptions-item>
      </t-descriptions>

      <t-divider content="详细信息" style="margin: 20px 0" />

      <t-descriptions column="1" :column="1" :column-width="['150px', 'auto']">
        <t-descriptions-item label="商品图库">
          <div class="gallery">
            <div
              v-for="(img, index) in galleryImages"
              :key="index"
              class="gallery-item"
            >
              <img :src="img" alt="商品图片" />
            </div>
          </div>
        </t-descriptions-item>

        <t-descriptions-item label="商品规格">
          <t-space direction="vertical" size="small">
            <t-tag
              v-for="(value, key) in specsObj"
              :key="key"
              variant="outline"
            >
              {{ key }}: {{ value }}
            </t-tag>
          </t-space>
        </t-descriptions-item>

        <t-descriptions-item label="商品详情">
          <div v-html="detail.detailHtml" class="detail-html"></div>
        </t-descriptions-item>

        <t-descriptions-item label="额外信息">
          <pre>{{ extraJsonObj }}</pre>
        </t-descriptions-item>
      </t-descriptions>
    </div>

    <div v-else class="empty">
      <t-empty description="未找到商品详情" />
    </div>

    <template #footer>
      <t-button @click="handleClose">关闭</t-button>
    </template>
  </t-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import commodityApi from '../../api/commodity';
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'

// 接收父组件参数
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  commodityId: {
    type: Number,
    default: null
  }
});

//  emits
const emit = defineEmits(['close']);

// 数据
const loading = ref(false);
const detail = ref(null);
const commodity = ref(null);
const galleryImages = ref([]);
const specsObj = ref({});
const extraJsonObj = ref({});

// 监听商品ID变化
watch(() => props.commodityId, (newVal) => {
  if (newVal && props.visible) {
    fetchData(newVal);
  }
}, { immediate: true });

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal && props.commodityId) {
    fetchData(props.commodityId);
  }
});

// 获取商品详情数据
const fetchData = async (id) => {
  try {
    loading.value = true;
    // 获取商品主信息
    // 注意：这里需要先获取商品主信息，实际项目中可能需要调整API
    const pageData = await commodityApi.getCommodityPage('', 1, 1);
    commodity.value = pageData.records.find(item => item.id === id) || null;

    // 获取商品详情
    const detailData = await commodityApi.getCommodityDetail(id);
    detail.value = detailData;

    // 解析JSON字段
    if (detailData?.gallery) {
      try {
        galleryImages.value = JSON.parse(detailData.gallery);
      } catch (e) {
        console.error('解析gallery失败', e);
        galleryImages.value = [];
      }
    }

    if (detailData?.specs) {
      try {
        specsObj.value = JSON.parse(detailData.specs);
      } catch (e) {
        console.error('解析specs失败', e);
        specsObj.value = {};
      }
    }

    if (detailData?.extraJson) {
      try {
        extraJsonObj.value = JSON.parse(detailData.extraJson);
      } catch (e) {
        console.error('解析extraJson失败', e);
        extraJsonObj.value = {};
      }
    }
  } catch (err) {
    MessagePlugin.error('获取商品详情失败');
    console.error(err);
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  emit('close');
};
</script>

<style scoped>
.loading {
  text-align: center;
  padding: 50px 0;
}

.empty {
  padding: 50px 0;
}

.detail-container {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.gallery {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.gallery-item img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border: 1px solid #eee;
}

.detail-html {
  line-height: 1.8;
}

.detail-html img {
  max-width: 100%;
  height: auto;
}
</style>
